package com.sztx.worker_monitor.core.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sztx.worker_monitor.core.service.UserService;
import com.sztx.worker_monitor.dataaccess.dao.mysql.UserMysqlDAO;
import com.sztx.worker_monitor.dataaccess.domain.UserDO;
import com.sztx.se.common.exception.BusinessException;
import com.sztx.se.common.util.secret.MD5Util;
import com.sztx.se.common.util.validate.ValidateUtil;
import com.sztx.se.core.service.impl.BaseServiceImpl;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService {

	@Autowired
	private UserMysqlDAO userMysqlDAO;

	public UserDO findByUsername(String username) {
		ValidateUtil.isNotBlank(username, "用户名不能为空");
		UserDO user = userMysqlDAO.findByUsername(username);
		return user;
	}
	
	@Transactional 
	@Override
	public Integer addUser(String username, String password, String nick, Integer sex, Integer age, Date birthday, String address, String tel, String email,
			String md5Key) {
		ValidateUtil.isNotBlank(username, "用户名不能为空");
		ValidateUtil.isNotBlank(password, "用户密码不能为空");

		// 根据用户名查询是否已经存在
		UserDO oldUser = userMysqlDAO.findByUsername(username);

		if (oldUser != null) {
			throw new BusinessException("该用户已经存在");
		}

		UserDO user = new UserDO();
		user.setUsername(username);
		user.setPassword(password);
		user.setNick(StringUtils.isBlank(nick) ? username : nick);
		user.setSex(sex);
		user.setAge(age);
		user.setBirthday(birthday);
		user.setAddress(address);
		user.setTel(tel);
		user.setEmail(email);
		user.setCreateUser(username);
		user.setUpdateUser(username);
		user.setStatus(UserDO.STATUS_NORMAL);
		userMysqlDAO.save(user);
		Integer userId = user.getId();

		if (userId == null || userId.intValue() <= 0) {
			throw new BusinessException("创建用户失败");
		}

		UserDO thisUser = userMysqlDAO.findByUsername(username);
		String encryptPword = generateMD5Password(username, password, thisUser.getCreateTime(), md5Key);
		thisUser.setPassword(encryptPword);
		userMysqlDAO.update(thisUser);

		return userId;
	}

	/**
	 * 生成MD5密码
	 * 
	 * @param username
	 * @param password
	 * @param createTime
	 * @param md5Key
	 * @return
	 */
	private String generateMD5Password(String username, String password, Date createTime, String md5Key) {
		return MD5Util.encryptWithKey(username + password + createTime.getTime(), md5Key);
	}
}
